package com.czsth.security;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

public class SecurityInterceptor implements Interceptor {

    public String intercept(ActionInvocation invocation) throws Exception {

        HttpServletRequest request = ServletActionContext.getRequest();

        String ticket = null;    //登录标记
        //1.验证是否登录:通过Cookie
        //ps:现在是因为跨域的问题，无法解决
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("sso.ticket")) {
                ticket = cookie.getValue();
                System.out.println("ok-->" + ticket);
//                cookie.setValue(ticket + "_" + new Random().nextInt());
//                HttpServletResponse response = ServletActionContext.getResponse();
//                response.addCookie(cookie);
                break;
            }
        }

        if (ticket == null) {
            //Cookie中没有用户登录信息，需要跳转去登录
            String source = request.getRequestURL().toString();

            HttpServletResponse response = ServletActionContext.getResponse();
            response.sendRedirect("http://localhost/sso/login_forward.action?app=admin&&source=" + source);
            return Action.NONE;
        } else {
            //已经有Ticket，可以去SSO系统获取登录信息
            return invocation.invoke();
        }
    }

    public void destroy() {
    }

    public void init() {
    }
}
